package com.boby.homecamera.db

import android.content.ContentValues
import android.database.Cursor
import android.database.sqlite.SQLiteDatabase
import androidx.core.database.getLongOrNull
import androidx.core.database.getStringOrNull

class UserTable(val database:SQLiteDatabase) {


     companion object {
         private   val TABLE_USER = "user"
         fun createTable(db: SQLiteDatabase) {

             db.execSQL(
                 """
            CREATE TABLE IF NOT EXISTS $TABLE_USER (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                userName TEXT NOT NULL,
                password TEXT NOT NULL,
                token TEXT ,
                refreshToken TEXT 
            );
            """.trimIndent()
             )
         }
     }


    fun insertUser(user: User): Long {
        val values = ContentValues().apply {
            put("userName", user.userName)
            put("password", user.password)
            put("token", user.token)
            put("refreshToken", user.refreshToken)
        }
        return database.insert(TABLE_USER, null, values)
    }
// var id: Long = -1,
//        var userName: String = "",
//        var password: String =  "",
//        var token: String? = null,
//        var refreshToken: String? = null
    fun updateVideo(user: User): Int {
        val values = ContentValues().apply {
            put("userName", user.userName)
            put("password", user.password)
            put("token", user.token)
            put("refreshToken", user.refreshToken)
        }
        return database.update(TABLE_USER, values, "id=?", arrayOf(user.id.toString()))
    }


    fun queryAllVideos(): List<User> {
        val videos = mutableListOf<User>()
        val cursor: Cursor = database.query(
            TABLE_USER,
            arrayOf("id", "userName", "password", "token", "refreshToken",),
            null, null, null, null, null
        )
        cursor.use {
            while (it.moveToNext()) {
                val user = User(
                    id = it.getLong(it.getColumnIndexOrThrow("id")),
                    userName = it.getString(it.getColumnIndexOrThrow("userName")),
                    password = it.getString(it.getColumnIndexOrThrow("password")),
                    token = it.getStringOrNull(it.getColumnIndexOrThrow("token")),
                    refreshToken = it.getStringOrNull(it.getColumnIndexOrThrow("refreshToken")),
                )
                videos.add(user)
            }
        }
        return videos
    }

    data class User(
        var id: Long = -1,
        var userName: String = "",
        var password: String =  "",
        var token: String? = null,
        var refreshToken: String? = null
    )
}


